package com.chushouya.order.rabbitmq.listener;

import com.general.framework.core.exception.BaseException;
import com.general.framework.core.exception.ViolationException;
import com.general.framework.core.lang.Jsons;
import com.chushouya.common.dto.QueueMessage;
import com.chushouya.order.dto.api.partnernotify.NotifyQueue;
import com.chushouya.order.service.admin.AlipaySubscribeService;
import com.chushouya.order.service.admin.OrderNotifyService;
import com.chushouya.order.service.admin.PartnerStatusNotifyService;
import com.fasterxml.jackson.databind.ObjectMapper;
import lombok.extern.slf4j.Slf4j;
import org.springframework.amqp.rabbit.annotation.Queue;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;

/**
 * 通知消息监听器
 * 
 * @author chushouya
 * @date 2025-08-14
 */
@Slf4j
@Component
public class NotifyMessageListener {

    @Resource
    private ObjectMapper objectMapper;
    
    @Resource
    private OrderNotifyService orderNotifyService;
    
    @Resource
    private PartnerStatusNotifyService partnerStatusNotifyService;
    
    @Resource
    private AlipaySubscribeService alipaySubscribeService;

    /**
     * 监听短信通知消息
     */
    @RabbitListener(queuesToDeclare = @Queue(name = "chushouya.notify.clerk.sms", durable = "true"))
    public void handleSmsNotifyMessage(QueueMessage<?> queueMessage) {
        try {
            log.info("收到短信通知消息: messageId={}, data={}", queueMessage.getMessageId(), queueMessage.getData());
            
            // 验证消息数据
            if (queueMessage.getData() == null) {
                log.error("短信通知消息数据为空: messageId={}", queueMessage.getMessageId());
                log.warn("数据为空的消息已处理，避免重复处理: messageId={}", queueMessage.getMessageId());
                return;
            }
            
            // 处理短信通知
            Long orderId = Long.valueOf(queueMessage.getData().toString());
            log.info("开始处理短信通知，订单ID: {}, messageId: {}", orderId, queueMessage.getMessageId());
            
            orderNotifyService.sendSmsToClerk(orderId);
            
            log.info("短信通知消息处理完成 - 消息ID: {}, 订单ID: {}", 
                    queueMessage.getMessageId(), orderId);
            
        } catch (ViolationException e) {
            log.error("短信通知消息验证错误: {}, messageId: {}", e.getMessage(), queueMessage.getMessageId());
            // 验证异常不抛出，避免消息重新入队
            log.warn("验证异常消息已处理，避免重复处理: messageId={}", queueMessage.getMessageId());
        } catch (BaseException e) {
            log.error("短信通知消息业务异常: {}, messageId: {}", e.getMessage(), queueMessage.getMessageId());
            // 业务异常不抛出，避免消息重新入队
            log.warn("业务异常消息已处理，避免重复处理: messageId={}", queueMessage.getMessageId());
        } catch (Exception e) {
            log.error("处理短信通知消息异常: {}, messageId: {}", e.getMessage(), queueMessage.getMessageId(), e);
            // 其他异常不抛出，避免消息重新入队
            log.warn("异常消息已处理，避免重复处理: messageId={}", queueMessage.getMessageId());
        }
    }

    /**
     * 监听微信通知消息
     */
    @RabbitListener(queuesToDeclare = @Queue(name = "chushouya.notify.clerk.wechat", durable = "true"))
    public void handleWechatNotifyMessage(QueueMessage<?> queueMessage) {
        try {
            log.info("收到微信通知消息: messageId={}, data={}", queueMessage.getMessageId(), queueMessage.getData());
            
            // 验证消息数据
            if (queueMessage.getData() == null) {
                log.error("微信通知消息数据为空: messageId={}", queueMessage.getMessageId());
                log.warn("数据为空的消息已处理，避免重复处理: messageId={}", queueMessage.getMessageId());
                return;
            }
            
            // 处理微信通知
            Long orderId = Long.valueOf(queueMessage.getData().toString());
            log.info("开始处理微信通知，订单ID: {}, messageId: {}", orderId, queueMessage.getMessageId());
            
            orderNotifyService.sendWechatToClerk(orderId);
            
            log.info("微信通知消息处理完成 - 消息ID: {}, 订单ID: {}", 
                    queueMessage.getMessageId(), orderId);
            
        } catch (ViolationException e) {
            log.error("微信通知消息验证错误: {}, messageId: {}", e.getMessage(), queueMessage.getMessageId());
            // 验证异常不抛出，避免消息重新入队
            log.warn("验证异常消息已处理，避免重复处理: messageId={}", queueMessage.getMessageId());
        } catch (BaseException e) {
            log.error("微信通知消息业务异常: {}, messageId: {}", e.getMessage(), queueMessage.getMessageId());
            // 业务异常不抛出，避免消息重新入队
            log.warn("业务异常消息已处理，避免重复处理: messageId={}", queueMessage.getMessageId());
        } catch (Exception e) {
            log.error("处理微信通知消息异常: {}, messageId: {}", e.getMessage(), queueMessage.getMessageId(), e);
            // 其他异常不抛出，避免消息重新入队
            log.warn("异常消息已处理，避免重复处理: messageId={}", queueMessage.getMessageId());
        }
    }

    /**
     * 监听订单状态通知消息
     */
    @RabbitListener(queuesToDeclare = @Queue(name = "chushouya.notify.order.user.status", durable = "true"))
    public void handleOrderStatusNotifyMessage(QueueMessage<?> queueMessage) {
        try {
            log.info("收到订单状态通知消息: messageId={}, data={}", queueMessage.getMessageId(), queueMessage.getData());
            
            // 验证消息数据
            if (queueMessage.getData() == null) {
                log.error("订单状态通知消息数据为空: messageId={}", queueMessage.getMessageId());
                log.warn("数据为空的消息已处理，避免重复处理: messageId={}", queueMessage.getMessageId());
                return;
            }
            
            // 处理订单状态通知
            Long orderId = Long.valueOf(queueMessage.getData().toString());
            log.info("开始处理订单状态通知，订单ID: {}, messageId: {}", orderId, queueMessage.getMessageId());
            
            orderNotifyService.orderStatusNotify(orderId);
            
            log.info("订单状态通知消息处理完成 - 消息ID: {}, 订单ID: {}", 
                    queueMessage.getMessageId(), orderId);
            
        } catch (ViolationException e) {
            log.error("订单状态通知消息验证错误: {}, messageId: {}", e.getMessage(), queueMessage.getMessageId());
            // 验证异常不抛出，避免消息重新入队
            log.warn("验证异常消息已处理，避免重复处理: messageId={}", queueMessage.getMessageId());
        } catch (BaseException e) {
            log.error("订单状态通知消息业务异常: {}, messageId: {}", e.getMessage(), queueMessage.getMessageId());
            // 业务异常不抛出，避免消息重新入队
            log.warn("业务异常消息已处理，避免重复处理: messageId={}", queueMessage.getMessageId());
        } catch (Exception e) {
            log.error("处理订单状态通知消息异常: {}, messageId: {}", e.getMessage(), queueMessage.getMessageId(), e);
            // 其他异常不抛出，避免消息重新入队
            log.warn("异常消息已处理，避免重复处理: messageId={}", queueMessage.getMessageId());
        }
    }

    /**
     * 监听合作商订单状态通知消息
     */
    @RabbitListener(queuesToDeclare = @Queue(name = "chushouya.notify.partner.order.status", durable = "true"))
    public void handlePartnerOrderStatusNotifyMessage(QueueMessage<?> queueMessage) {
        try {
            log.info("收到合作商订单状态通知消息: messageId={}, data={}", queueMessage.getMessageId(), queueMessage.getData());
            
            // 验证消息数据
            if (queueMessage.getData() == null) {
                log.error("合作商订单状态通知消息数据为空: messageId={}", queueMessage.getMessageId());
                log.warn("数据为空的消息已处理，避免重复处理: messageId={}", queueMessage.getMessageId());
                return;
            }

            // 创建NotifyQueue对象并调用服务
            NotifyQueue notifyQueue = Jsons.parseObject(queueMessage.getData().toString(), NotifyQueue.class);
            log.info("开始处理合作商订单状态通知，messageId: {}, 订单: {}", queueMessage.getMessageId(), notifyQueue);
            
            partnerStatusNotifyService.controlOrderNotify(notifyQueue);
            
            log.info("合作商订单状态通知消息处理完成 - 消息ID: {}, 订单: {}",
                    queueMessage.getMessageId(), notifyQueue);
            
        } catch (ViolationException e) {
            log.error("合作商订单状态通知消息验证错误: {}, messageId: {}", e.getMessage(), queueMessage.getMessageId());
            // 验证异常不抛出，避免消息重新入队
            log.warn("验证异常消息已处理，避免重复处理: messageId={}", queueMessage.getMessageId());
        } catch (BaseException e) {
            log.error("合作商订单状态通知消息业务异常: {}, messageId: {}", e.getMessage(), queueMessage.getMessageId());
            // 业务异常不抛出，避免消息重新入队
            log.warn("业务异常消息已处理，避免重复处理: messageId={}", queueMessage.getMessageId());
        } catch (Exception e) {
            log.error("处理合作商订单状态通知消息异常: {}, messageId: {}", e.getMessage(), queueMessage.getMessageId(), e);
            // 其他异常不抛出，避免消息重新入队
            log.warn("异常消息已处理，避免重复处理: messageId={}", queueMessage.getMessageId());
        }
    }

    /**
     * 监听支付宝订阅消息
     */
    @RabbitListener(queuesToDeclare = @Queue(name = "chushouya.alipay.subscribe.message", durable = "true"))
    public void handleAlipaySubscribeMessage(QueueMessage<?> queueMessage) {
        try {
            log.info("收到支付宝订阅消息: messageId={}, data={}", queueMessage.getMessageId(), queueMessage.getData());
            
            // 验证消息数据
            if (queueMessage.getData() == null) {
                log.error("支付宝订阅消息数据为空: messageId={}", queueMessage.getMessageId());
                log.warn("数据为空的消息已处理，避免重复处理: messageId={}", queueMessage.getMessageId());
                return;
            }
            
            String dataStr = queueMessage.getData().toString();
            Long orderId;
            String subscribeType = "ORDER_SUCCESS"; // 默认类型
            
            try {
                // 尝试解析JSON格式的消息数据
                com.alibaba.fastjson.JSONObject messageData = com.alibaba.fastjson.JSONObject.parseObject(dataStr);
                orderId = messageData.getLong("orderId");
                subscribeType = messageData.getString("subscribeType");
                if (subscribeType == null) {
                    subscribeType = "ORDER_SUCCESS";
                }
            } catch (Exception e) {
                // 如果解析失败，当作纯订单ID处理（兼容旧格式）
                orderId = Long.valueOf(dataStr);
                log.info("使用兼容模式解析订单ID: {}", orderId);
            }
            
            log.info("开始处理支付宝订阅消息，订单ID: {}, 订阅类型: {}, messageId: {}", 
                    orderId, subscribeType, queueMessage.getMessageId());
            
            // 根据订阅类型调用不同的处理方法
            switch (subscribeType) {
                case "ORDER_SUCCESS":
                    alipaySubscribeService.sendOrderSuccessNotify(orderId);
                    break;
                case "RECYCLE_CANCEL":
                    alipaySubscribeService.sendRecycleCancelNotify(orderId);
                    break;
                case "PAYMENT_RECEIVED":
                    alipaySubscribeService.sendPaymentReceivedNotify(orderId);
                    break;
                default:
                    log.warn("未知的订阅消息类型: {}, 使用默认处理", subscribeType);
                    alipaySubscribeService.sendOrderSuccessNotify(orderId);
                    break;
            }
            
            log.info("支付宝订阅消息处理完成 - 消息ID: {}, 订单ID: {}, 订阅类型: {}", 
                    queueMessage.getMessageId(), orderId, subscribeType);
            
        } catch (ViolationException e) {
            log.error("支付宝订阅消息验证错误: {}, messageId: {}", e.getMessage(), queueMessage.getMessageId());
            // 验证异常不抛出，避免消息重新入队
            log.warn("验证异常消息已处理，避免重复处理: messageId={}", queueMessage.getMessageId());
        } catch (BaseException e) {
            log.error("支付宝订阅消息业务异常: {}, messageId: {}", e.getMessage(), queueMessage.getMessageId());
            // 业务异常不抛出，避免消息重新入队
            log.warn("业务异常消息已处理，避免重复处理: messageId={}", queueMessage.getMessageId());
        } catch (Exception e) {
            log.error("处理支付宝订阅消息异常: {}, messageId: {}", e.getMessage(), queueMessage.getMessageId(), e);
            // 其他异常不抛出，避免消息重新入队
            log.warn("异常消息已处理，避免重复处理: messageId={}", queueMessage.getMessageId());
        }
    }
}
